import React from "react";
import { historyShape } from "src/propType";
import PropTypes from "prop-types";
export default class ErrorBoundary extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            error: null,
        };
    }

    componentDidCatch(error, info) {
        if (String(error).includes("Loading chunk")) {
            window.location.reload();
            return;
        }

        this.setState({
            error,
        });

        // 设置崩溃以后显示的UI
        // 上传错误日志
    }

    render() {
        if (this.state.error) {
            // 如果页面崩溃，则显示下面的UI
            return process.env.NODE_ENV === "development" ? (
                <div
                    style={{
                        justifyContent: "center",
                        alignItems: "center",
                        width: "100%",
                        height: "100%",
                    }}
                >
                    <p style={{ color: "red" }}>
                        {this.state.error && this.state.error.toString()}
                    </p>
                </div>
            ) : (
                <Error history={this.props.children ? this.props.children.props.history : null} />
            );
        }
        return this.props.children;
    }
}

function Error(props) {
    return (
        <div className="error">
            <div className="img">
                <div
                    className="link"
                    onClick={() => {
                        props.history.go(0);
                    }}
                ></div>
            </div>
        </div>
    );
}

ErrorBoundary.propTypes = {
    children: PropTypes.element,
};

Error.propTypes = {
    history: historyShape,
};
